//
//  DLNAPlayManager.m
//  ttkan
//
//  Created by jackcheng on 2017/10/12.
//  Copyright © 2017年 xiangyue. All rights reserved.
//

#import "DLNAPlayManager.h"
#import "Stop.h"
#import "Play.h"
#import "Seek.h"
#import "Pause.h"
#import "ControlPoint.h"
#import "SetURI.h"
#import "GetPositionInfo.h"
#import "ModelUtils.h"

@interface DLNAPlayManager()<DeviceChangeDelegate>

@property (nonatomic,copy) NSString *currentUrl;

@property (nonatomic,strong) Device *currentDevice;
@property (nonatomic,strong) ControlPoint *mediaControl;
@property (nonatomic,strong) ControlPoint *renderControl;
@property (nonatomic,strong) NSMutableArray *renders;
@property (nonatomic,assign) float seekTime;
@property (nonatomic,strong) NSLock *lock;

@property (nonatomic,assign) BOOL isUpdateProgress;

@end

NSNotificationName const DLNAStartPlayNotification = @"DLNAStartPlayNotification";
NSNotificationName const DLNAStopPlayNotification  = @"DLNAStopPlayNotification";

@implementation DLNAPlayManager

- (NSLock *)lock {
	if (_lock == nil) {
		_lock = [[NSLock alloc] init];
	}
	return _lock;
}


+ (DLNAPlayManager *)manager {
	static DLNAPlayManager *mgr = nil;
	static dispatch_once_t onceToken;
	dispatch_once(&onceToken, ^{
		mgr = [[DLNAPlayManager alloc] init];
	});
	return mgr;
}





- (void)playWithdevice:(Device *)device comeplete:(void (^)(BOOL))comepleteBlock{

	_isOnTV = YES;
	__weak __typeof(self) weakSelf = self;
	if (_mediaControl) {
		Stop *stopAction = [[Stop alloc] initWithSuccess:^{
			weakSelf.isUpdateProgress = NO;
			weakSelf.mediaControl = [[ControlPoint alloc] initWithService:device.mediaControlService];
			weakSelf.renderControl = [[ControlPoint alloc] initWithService:device.renderingControlService];
			weakSelf.serviceId = device.uuid;
			if (comepleteBlock) {
				comepleteBlock(YES);
			}
			[[NSNotificationCenter defaultCenter] postNotificationName:DLNAStartPlayNotification object:nil];
			
		} failure:^(NSError *error) {
			weakSelf.mediaControl = [[ControlPoint alloc] initWithService:device.mediaControlService];
			weakSelf.renderControl = [[ControlPoint alloc] initWithService:device.renderingControlService];
			weakSelf.serviceId = device.uuid;
			if (comepleteBlock) {
				comepleteBlock(YES);
			}
			[[NSNotificationCenter defaultCenter] postNotificationName:DLNAStartPlayNotification object:nil];
		}];
		[_mediaControl executeAction:stopAction];
	}else {
		_mediaControl = [[ControlPoint alloc] initWithService:device.mediaControlService];
		_renderControl = [[ControlPoint alloc] initWithService:device.renderingControlService];
		_serviceId = device.uuid;
		if (comepleteBlock) {
			comepleteBlock(YES);
		}
		[[NSNotificationCenter defaultCenter] postNotificationName:DLNAStartPlayNotification object:nil];
	}
	
	
	
}
//@"<DIDL-Lite xmlns=\"urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:sec=\"http://www.sec.co.kr/\" xmlns:upnp=\"urn:schemas-upnp-org:metadata-1-0/upnp/\"><item id=\"f-0\" parentID=\"0\" restricted=\"0\"><dc:title>Video</dc:title><dc:creator>Anonymous</dc:creator><upnp:class>object.item.videoItem</upnp:class><res protocolInfo=\"http-get:*:video/*:DLNA.ORG_OP=01;DLNA.ORG_CI=0;DLNA.ORG_FLAGS=01700000000000000000000000000000\" sec:URIType=\"public\">%@</res></item></DIDL-Lite>"

- (NSString *)mateDataWithTitle:(NSString *)title {
	if (title.length == 0) {
		title = @"未知";
	}
	return [NSString stringWithFormat:@"<DIDL-Lite xmlns=\"urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:sec=\"http://www.sec.co.kr/\" xmlns:upnp=\"urn:schemas-upnp-org:metadata-1-0/upnp/\"><item id=\"f-0\" parentID=\"0\" restricted=\"0\"><dc:title>%@</dc:title><dc:creator>Anonymous</dc:creator><upnp:class>object.item.videoItem</upnp:class><res protocolInfo=\"http-get:*:video/*:DLNA.ORG_OP=01;DLNA.ORG_CI=0;DLNA.ORG_FLAGS=01700000000000000000000000000000\" sec:URIType=\"public\">%@</res></item></DIDL-Lite>", title,_currentUrl];
}

- (void)playUrl:(NSString *)url title:(NSString *)title startTime:(NSTimeInterval)time{
	__weak __typeof(self) weakSelf = self;
	Stop *stopAction = [[Stop alloc] initWithSuccess:^{
		weakSelf.isUpdateProgress = NO;
		[weakSelf relodUrl:url title:title startTime:time];
	} failure:^(NSError *error) {
		[weakSelf relodUrl:url title:title startTime:time];
	}];
	[_mediaControl executeAction:stopAction];
	
	
}

- (void)relodUrl:(NSString *)url title:(NSString *)title startTime:(NSTimeInterval)time {
	__weak __typeof(self) weakSelf = self;
	SetURI *setUriAction = [[SetURI alloc] initWithURI:url metaData:[self mateDataWithTitle:title] success:^{
		weakSelf.playBack = DLNAPlayBackSucess;
		weakSelf.isUpdateProgress = YES;
		weakSelf.isPlaying = YES;
	} failure:^(NSError *error) {
		weakSelf.playBack = DLNAPlayBackFailed;
		weakSelf.isPlaying = NO;
	}];
	[_mediaControl executeAction:setUriAction];
	
	[[NSNotificationCenter defaultCenter] postNotificationName:DLNAStartPlayNotification object:nil];
}

- (void)play {
	Play *playAction = [[Play alloc] initWithSuccess:^{
		
	} failure:^(NSError *error) {
		NSLog(@"播放失败");
	}];
	
	[_mediaControl executeAction:playAction];
}



- (void)pause {
	Pause *pauseAction = [[Pause alloc] initWithSuccess:^{
		
	} failure:^(NSError *error) {
		NSLog(@"暂停失败");
	}];
	
	[_mediaControl executeAction:pauseAction];
}

- (void)stop {
	__weak __typeof(self) weakSelf = self;
	Stop *stopAction = [[Stop alloc] initWithSuccess:^{
		weakSelf.isUpdateProgress = NO;
		weakSelf.isPlaying = NO;
		[[NSNotificationCenter defaultCenter] postNotificationName:DLNAStopPlayNotification object:nil];
	} failure:^(NSError *error) {
		weakSelf.isPlaying = NO;
		[[NSNotificationCenter defaultCenter] postNotificationName:DLNAStopPlayNotification object:nil];
	}];
	[_mediaControl executeAction:stopAction];
}

- (void)seekTo:(NSInteger)time {
	Seek *seekAction = [[Seek alloc] initWithTarget:[ModelUtils timeStringFromInteger:time] success:^{
		
	} failure:^(NSError *error) {
		NSLog(@"快进失败");
	}];
	
	[_mediaControl executeAction:seekAction];
}



- (float)currentTime {
	
	return 0;
}

- (float)durationTime {
	
	return 0;
}

- (void)getPositionInfo {
	__weak __typeof(self) weakSelf = self;
	GetPositionInfo *getPosInfoAction = [[GetPositionInfo alloc] initWithSuccess:^(NSString *currentDuration, NSString *totalDuration) {
		dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//			if ([totalDuration isEqualToString:@"00:00:00"]) {
//				weakSelf.isUpdateProgress = NO;
//				weakSelf.playBack = DLNAPlayBackFailed;
//			}
			if (weakSelf.isUpdateProgress) {
				[weakSelf getPositionInfo];
			}
		});
	} failure:^(NSError *error) {
		weakSelf.playBack = DLNAPlayBackFailed;
	}];
	
	[_mediaControl executeAction:getPosInfoAction];
}

- (void)setIsOnTV:(BOOL)isOnTV {
	self.dlnaBtn.hidden = !_isOnTV;
}

- (void)search {
	self.isSearching = YES;
	[DLNAUpnpServer shareServer].delegate = self;
	[[DLNAUpnpServer shareServer] startAndSearch:YES];
}

- (void)onChange {
	self.deviceList = [NSMutableArray arrayWithArray:[[DLNAUpnpServer shareServer] getDeviceList]];
}

- (void)searchEnd {
	self.isSearching = NO;
}

- (BOOL)isOnTVWithMid:(NSInteger)mid {
	
	return  _mid == mid;
}

- (UIButton *)dlnaBtn {
	if (_dlnaBtn == nil) {
		_dlnaBtn = [[UIButton alloc] initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width - 80, [UIScreen mainScreen].bounds.size.height - 210, 60, 60)];
		[_dlnaBtn setImage:[UIImage imageNamed:@"home_dlna_icon"] forState:UIControlStateNormal];
		_dlnaBtn.hidden = YES;
	}
	return _dlnaBtn;
}

@end
